package com.sciener.control;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class getPhotoServlet extends HttpServlet{

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		
		String filename = request.getParameter("filename");
		//String filename = "/header/1/1.jpg";
		int scale = Integer.valueOf(request.getParameter("scale"));
		String photoRootPath = request.getSession().getServletContext().getRealPath("");
		String photoPath = photoRootPath+filename;
		
		OutputStream os = response.getOutputStream();
		FileInputStream fis = new FileInputStream(photoPath);
		scaleImage(fis,os,scale);
		fis.close();
	}
	
	public void scaleImage(InputStream imgInputStream,OutputStream imgOutputStream,int scale)
	{
		try{
		Image src= javax.imageio.ImageIO.read(imgInputStream);
		int width =(int)(src.getWidth(null)*scale/100.0);
		int height = (int)(src.getHeight(null)*scale/100.0);
		BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		bufferedImage.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imgOutputStream);
		encoder.encode(bufferedImage);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	

}
